package org.mini.extension
{
	import com.shine.manager.StageManager;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.utils.getDefinitionByName;
	
	public class MainLoader extends MovieClip
	{
		protected var _application_name:String="Application";
		
		public function MainLoader()
		{
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, eventsHandler,false,0,true);
		}
		
		protected function init():void
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode=StageScaleMode.NO_SCALE;
			
			if(StageManager.getStage()==null){
				StageManager.initStage(stage);
			}
		}
		
		private function eventsHandler(e:Event):void
		{
			switch(e.type)
			{
				case Event.ADDED_TO_STAGE:
					init();
					createLoading();
					removeEventListener(Event.ADDED_TO_STAGE, eventsHandler);
					addEventListener(Event.ENTER_FRAME, eventsHandler);
					break;
				
				case Event.ENTER_FRAME:
					if(isNaN(loaderInfo.bytesTotal)) return;
					
					var percent:int = (loaderInfo.bytesLoaded / loaderInfo.bytesTotal) * 100 >> 0;
					onProgress(percent);
					
					if (loaderInfo.bytesLoaded == loaderInfo.bytesTotal)
					{											
						removeEventListener(Event.ENTER_FRAME, eventsHandler);
						nextFrame();
						initApp();
					}
					break;
			}
		}
		
		protected function createLoading():void
		{
			
		}
		
		protected function onProgress(percent:uint):void
		{
			
		}
		
		protected function initApp():void
		{
			var appClass:Class = getDefinitionByName(_application_name) as Class;			
			if (appClass != null)
			{
				var app:Object = new appClass();
				addChild(app as DisplayObject);
			}
		}
	}
}